package com.itheima.config;

import com.itheima.pojo.Configuration;
import com.itheima.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

public class XMLMapperBuilder {
    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration=configuration;
    }

    public void parse(InputStream resourceAsStream) throws DocumentException {
        Document document = new SAXReader().read(resourceAsStream);
        Element rootElement = document.getRootElement();
        List<Element> selectList = rootElement.selectNodes("//select");
        String namespace = rootElement.attributeValue("namespace");
        for (Element element : selectList) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql=element.getTextTrim();
            //封装到mapperStatement对象中
            String statementId=namespace+"."+id;
            MappedStatement mappedStatement = new MappedStatement(statementId, resultType, parameterType, sql,"select");
            configuration.getMappedStatementMap().put(statementId,mappedStatement);
        }
    }
}
